﻿



namespace WPAChess
{
    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.IO;
    using System.Windows.Markup;
    using System.Windows.Resources;
    /// <summary>
    /// Lop dung de load quan co tu Resources xaml
    /// </summary>
    public class Piece : UserControl
    {   
        /* khai bao doi tuong ve trong usercontrol */
        private Canvas graphic;
        /// <summary>
        /// Khoi tao mot quan co Resource la resourceName
        /// </summary>
        /// <param name="resourceName">kieu string, ten du lieu quan co thuoc loai xaml resources</param>
        public Piece(string resourceName)
        {
            StreamResourceInfo res = Application.GetResourceStream(new Uri("WPAChess;component/Pieces/" + resourceName, UriKind.Relative));  //lay thong tin nguon du lieu
            StreamReader reader = new StreamReader(res.Stream); //Dua thong tin nguon du lieu vao StreamReader

            this.graphic = (Canvas)XamlReader.Load(reader.ReadToEnd()); //ve doi tuong duoc load vao StreanReader
            this.Content = this.graphic; //tao noi dung UserControl
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class PiecesFactory
    {
        //private static readonly string[] pieces = new string[] { null, "BlackPawn.xaml", "BlackKnight.xaml", "BlackBishop.xaml", "BlackRook.xaml", "BlackQueen.xaml", "BlackKing.xaml", null,
        //               null, "WhitePawn.xaml", "WhiteKnight.xaml", "WhiteBishop.xaml", "WhiteRook.xaml", "WhiteQueen.xaml", "WhiteKing.xaml", null };

        private static readonly string[] pieces = new string[] { null, "WhitePawn.xaml", "WhiteKnight.xaml", "WhiteBishop.xaml", "WhiteRook.xaml", "WhiteQueen.xaml", "WhiteKing.xaml", null,
                       null,"BlackPawn.xaml", "BlackKnight.xaml", "BlackBishop.xaml", "BlackRook.xaml", "BlackQueen.xaml", "BlackKing.xaml" , null };
        /// <summary>
        /// Tao quan co
        /// </summary>
        /// <param name="type">Kieu int, chi muc trong tap hop cac quan co</param>
        /// <returns>Piece</returns>
        public Piece CreatePiece(int type)
        {
            try
            {
                string pieceName = PiecesFactory.pieces[type & 0xF]; //type & 0xF: type la loai nguyen duong

                if (pieceName != null)
                {
                    return new Piece(pieceName);
                }

                return null;
            }
            catch
            {
                return null;
            }
        }
    }
}
